package com.li.login;

import com.li.domain.Users;
import com.li.utils.DataSourceUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import javax.servlet.http.*;
import java.io.IOException;
import java.sql.SQLException;

/**
 * @Author liyuefan
 * @Date ${Date}
 * Description
 */
public class Login extends javax.servlet.http.HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        response.setCharacterEncoding("utf-8");

        //从表单获取提交数据
        String username = request.getParameter("username");
        String upassword = request.getParameter("upassword");
        //判空操作
        if(username == null || upassword == null){
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
        //与数据库进行比对
        QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
        Object[] params = {username,upassword};
        String sql = "select * from user_info_test where USER_NAME = ? and USER_PASSWORD = ?";
        Users users = null;
        try {
            users = runner.query(sql, new BeanHandler<Users>(Users.class), params);
            System.out.println(users.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }

        if(users != null){
            //登陆成功
            //将登录的用户写入session并跳转到首页
            request.getSession().setAttribute("users", users);
            System.out.println(users.toString());
            System.out.println(1);
            response.sendRedirect(request.getContextPath());
        }else{
            //登录失败，显示错误信息,跳转到登录页面
            request.setAttribute("LoginInfo", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request,response);
        }
    }
}
